package com.bdtop.dbl.ui.activities.fragments;

import java.util.ArrayList;
import java.util.List;

import org.litepal.crud.DataSupport;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bdtop.dbl.BaseFragment;
import com.bdtop.dbl.DBLApplication;
import com.bdtop.dbl.R;
import com.bdtop.dbl.bluetooth.BluetoothLeService;
import com.bdtop.dbl.db.model.DBLDeviceInfo;
import com.bdtop.dbl.model.DeviceInfo;
import com.bdtop.dbl.ui.activities.main.MainActivity;
import com.bdtop.dbl.ui.adapters.BleDeviceListAdapter;
import com.bdtop.dbl.ui.view.RadarScanView;
import com.bdtop.dbl.utils.Constants;
import com.bdtop.dbl.utils.DBLDebug;
import com.bdtop.dbl.utils.ImageUtils;
import com.bdtop.dbl.utils.Preferences;
import com.bdtop.dbl.utils.SystemUtils;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class BesideFragment extends BaseFragment implements OnItemClickListener {

	private BleDeviceListAdapter UIListAdapter;

	@Override public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		registerBleReceiver();

		UIListAdapter = new BleDeviceListAdapter(holder);
	}

	@Override public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		startBleService();
		bindBLeService();

		if (SystemUtils.supportBLE(holder)) {
			mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
				@Override public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
					getActivity().runOnUiThread(new Runnable() {
						@Override public void run() {
							DBLDebug.logd("onLeScan... mac:" + device.getAddress() + ", name:" + device.getName());
							if(Constants.ble_SuiYiZhao.equals(device.getName())){
								UIListAdapter.addDevice(device);	
							}
						}
					});
				}
			};
		}
	}

	public void letBluetoothEnable() {
		Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
		startActivityForResult(enableBtIntent, 1234);
	}

	@Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// User chose not to enable Bluetooth.
		if (requestCode == 1234 && resultCode == Activity.RESULT_OK) {
			if (!isHidden() && txSearch != null) {
				txSearch.setText(R.string.search_device);
				layoutReSearch.performClick();
			}
			return;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
		@Override public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
				
				mBesideHandler.removeMessages(MSG_STOP_SCAN_BY_TIME_OUT);
				DBLDebug.logd("BesideFragment mGattUpdateReceiver Remote device connected");
				needScan = false; // 之后直接重连

				if (mBluetoothLeService == null) {
					DBLDebug.loge("BesideFragment mGattUpdateReceiver onReceive() mBluetoothLeService null");
					return;
				}
				String connMac = mBluetoothLeService.getBluetoothDeviceAddress();
				
				Preferences.saveDefaultMacInfo(connMac); // 第一次连接，保存默认设置参数
				
				String rebindImei = ((MainActivity) holder).rebindImei;
				DBLDebug.logd("BesideFragment connMac:" + connMac + ",rebindImei:" + rebindImei);
				if (!TextUtils.isEmpty(rebindImei)) {
					String imei = Preferences.getImeiForMac(connMac);
					if(!hidden && !rebindImei.equals(imei)){
						showRenindDialog(connMac, rebindImei);
					}
				} else {
					String bindImei = Preferences.getImeiForMac(connMac);
					DBLDebug.logd("BesideFragment bindImei :" + (TextUtils.isEmpty(bindImei)));
					if (TextUtils.isEmpty(bindImei)) {
						if (!hidden) {
							showBindDialog(connMac);
						}
					} else {
						DBLDebug.loge("mGattUpdateReceiver to resetBleDeviceHead");
						resetBleDeviceHead(bindImei);
						DBLDebug.loge("updateUIAboutDeviceInfo to resetBleDeviceName");
						resetBleDeviceName();
					}
				}
				// 还原 重新绑定的标志
				MainActivity.currAction = -1;
			} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
				DBLDebug.logd("BesideFragment mGattUpdateReceiver Remote device disconnected");
				// 重新绑定的标志
				if (MainActivity.currAction == MainActivity.ACTION_BLE_RESEARCH) {
					return;
				}
				doUIupdate(false);
			} else if (BluetoothLeService.ACTION_READ_REMOTE_RSSI.equals(action)) {
				txRssi.setText(String.format(getString(R.string.rssi), Math.abs(intent.getIntExtra("rssi", 0))));
				radarView.stopScanning();
				hiddenScanDeviceListView();
			} else if (BluetoothLeService.ACTION_READ_REMOTE_DISTANCE.equals(action)) {
				updateUIAboutDeviceInfo(intent.getDoubleExtra("distance", 0d));
			} else if(BluetoothLeService.ACTION_GATT_RETRY_CONNECT.equals(action)) {
				doUIupdate();
			}
		}
	};

	private void stopScanDeviceList() {
		mBesideHandler.removeMessages(MSG_STOP_SCAN);
		mBesideHandler.sendEmptyMessage(MSG_STOP_SCAN);
	}

	public void startScanDeviceList() {
//		isScanOver = false;
		mBesideHandler.removeMessages(MSG_TO_CONNECT);
		mBesideHandler.sendEmptyMessage(MSG_TO_CONNECT);
		
		//fix 如果是呼叫状态时（此时按钮显示的是“停止”），点击“断开”，然后重新检测连接，按钮还是“停止”，没有恢复为“呼叫"
		layoutCall.setTag("call");
		txCall.setText(R.string.call);
//		mHandler.removeCallbacks(stopCall);
	}

	private static final int MSG_STOP_SCAN = 2;
	private static final int MSG_STOP_SCAN_BY_TIME_OUT = 3;
	private static final int MSG_TO_CONNECT = 5;
	
//	public static boolean isScanOver =false;

	private final Handler mBesideHandler = new Handler() {
		@Override public void handleMessage(Message msg) {
			if (mBluetoothLeService != null) {
				switch (msg.what) {
				case MSG_STOP_SCAN:
					DBLDebug.logd("BesideFragment mBesideHandler MSG_STOP_SCAN");
					DBLDebug.loge("BesideFragment stopLeScan ");
					mBluetoothLeService.stopLeScan(mLeScanCallback);
					doUIupdate();
					break;
				case MSG_STOP_SCAN_BY_TIME_OUT:
					DBLDebug.logd("BesideFragment mBesideHandler MSG_STOP_SCAN_BY_TIME_OUT");
					DBLDebug.loge("BesideFragment stopLeScan ");
					mBluetoothLeService.stopLeScan(mLeScanCallback);

					if (UIListAdapter.getCount() < 1 && !mBluetoothLeService.isConnected()) {
						if(!isHidden()){
							showToast(R.string.none_device);	
						}
						
//						isScanOver = true;
						doUIupdate( false );
					} else {
						showScanDeviceListView();
					}

					break;
				case MSG_TO_CONNECT:
					DBLDebug.logd("BesideFragment mBesideHandler MSG_TO_CONNECT");
					radarView.startScanning(true);
					mBesideHandler.removeMessages(MSG_STOP_SCAN_BY_TIME_OUT);
					mBesideHandler.sendEmptyMessageDelayed(MSG_STOP_SCAN_BY_TIME_OUT, 5000);
					needScan = true; // 每次都重新扫描
					if (needScan) {
						DBLDebug.loge("BesideFragment startLeScan ");
						UIListAdapter.clearDevice();
						mBluetoothLeService.startLeScan(mLeScanCallback);
					} else {
						DBLDebug.loge("BesideFragment retry Conntect");
						mBluetoothLeService.tryConnectLastBluetoothDevice();
					}
					break;
				}
			}
		}
	};

	// Device scan callback.
	private BluetoothAdapter.LeScanCallback mLeScanCallback;

	private boolean needScan = true;

	private View layoutDeviceFun, layoutReSearch, layoutScanResult, layoutDuanKai, layoutCall, layoutBleDevicePart;
	private View layoutStop;
	private RadarScanView radarView;
	private TextView txSearch, txRssi, txDebugData, txBleDevice, txCall;
	private ImageView imgBleDevice;
	private ListView listView;

	@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		FrameLayout view = (FrameLayout) inflater.inflate(R.layout.fragment_beside, container, false);

		radarView = (RadarScanView) view.findViewById(R.id.radar_view);
		layoutCall = view.findViewById(R.id.layout_call);
		layoutCall.setOnClickListener(onClickListener);
		layoutCall.setTag("call");
		layoutDuanKai = view.findViewById(R.id.layout_duankai);
		layoutDuanKai.setOnClickListener(onClickListener);
		layoutDeviceFun = view.findViewById(R.id.layout_device_fun);
		layoutDeviceFun.setVisibility(View.GONE);
		layoutReSearch = view.findViewById(R.id.layout_search);
		layoutReSearch.setVisibility(View.GONE);
		layoutReSearch.setOnClickListener(onClickListener);
		
		layoutStop = view.findViewById(R.id.layout_stop);
		layoutStop.setOnClickListener(onClickListener);
		

		txCall = (TextView) view.findViewById(R.id.tx_call);
		txSearch = (TextView) view.findViewById(R.id.tx_search);
		txRssi = (TextView) view.findViewById(R.id.tx_rssi);
		txDebugData = (TextView) view.findViewById(R.id.tx_debugdata);
		txDebugData.setVisibility(View.GONE);

		layoutBleDevicePart = view.findViewById(R.id.layout_ble_device_part);
		imgBleDevice = (ImageView) view.findViewById(R.id.img_ble_device);
		txBleDevice = (TextView) view.findViewById(R.id.tx_ble_device);
		layoutScanResult = view.findViewById(R.id.layout_scan_result);
		layoutScanResult.setVisibility(View.GONE);

		listView = (ListView) view.findViewById(R.id.listview);
		listView.setAdapter(UIListAdapter);
		listView.setOnItemClickListener(this);

		doUIupdate();
		return view;
	}

//	private Runnable stopCall = new Runnable() {
//		@Override public void run() {
//			layoutCall.setTag("call");
//			txCall.setText(R.string.call);
//		}
//	};

	private OnClickListener onClickListener = new OnClickListener() {
		@Override public void onClick(View view) {
			if (mBluetoothLeService != null) {
				switch (view.getId()) {
				case R.id.layout_search:
					if (!SystemUtils.supportBLE(holder)) {
						showToast(R.string.donot_support_ble);
						return;
					}
					if (mBluetoothLeService.isEnable()) {
						hiddenScanDeviceListView();
						startScanDeviceList();
						layoutReSearch.setVisibility(View.GONE);
						txSearch.setText(R.string.re_search);
					} else {
						letBluetoothEnable();
						txSearch.setText(R.string.open_bluetooth);
					}
					break;
				case R.id.layout_call:
//					letBtnCallInterval();
//					if (layoutCall.getTag().toString().equals("call")) {
//						mBluetoothLeService.requestCall(5);
//						layoutCall.setTag("stop");
//						txCall.setText(R.string.stop);
//						mHandler.removeCallbacks(stopCall);
//						mHandler.postDelayed(stopCall, 30000);
//					} else {
//						mBluetoothLeService.requestStopAlert(5);
//						layoutCall.setTag("call");
//						txCall.setText(R.string.call);
//						mHandler.removeCallbacks(stopCall);
//					}
					mBluetoothLeService.requestCall(5);
					break;
				case R.id.layout_stop:
					mBluetoothLeService.requestStopAlert(5);
					break;
				case R.id.layout_duankai:
					mBluetoothLeService.disconnect();
					layoutDuanKai.setEnabled(false);
					break;
				}
			}
		}
	};

//	private void letBtnCallInterval() {
//		mHandler.removeCallbacks(letBtnCallEnable);
//		layoutCall.setEnabled(false);
//		mHandler.postDelayed(letBtnCallEnable, 500);
//	}
//
//	private Runnable letBtnCallEnable = new Runnable() {
//		@Override public void run() {
//			layoutCall.setEnabled(true);
//		}
//	};

	public String getConnectedBluetoothDeviceAddress() {
		if (mBluetoothLeService != null) {
			return mBluetoothLeService.getBluetoothDeviceAddress();
		}
		return null;
	}

	private void showScanDeviceListView() {
		////////////////////////////////
		if (UIListAdapter.getList().size() == 1 && holder != null) {
			mDevice = UIListAdapter.getList().get(0);
			
			String address = Preferences.getLastConnectBluetoothDeviceAddress(holder);
			if(!TextUtils.isEmpty(address) && address.equals(mDevice.getAddress())){
				if (mBluetoothLeService != null) {  // 自动去连上上一次连接的设备
					mBluetoothLeService.connect(mDevice.getAddress());
					doUIupdate(); // connecting
				}
				return;	
			}
		}
        ////////////////////////////////
		radarView.stopScanning();
		if (layoutScanResult.getVisibility() != View.VISIBLE) {
			layoutScanResult.setVisibility(View.VISIBLE);
			layoutScanResult.startAnimation(AnimationUtils.loadAnimation(holder, R.anim.scale_in_left_top));
		}
		
		layoutReSearch.setVisibility(View.VISIBLE);
	}

	private void hiddenScanDeviceListView() {
		if (layoutScanResult.getVisibility() != View.GONE) {
			layoutScanResult.startAnimation(AnimationUtils.loadAnimation(holder, R.anim.scale_out_right_bottom));
			layoutScanResult.setVisibility(View.GONE);
		}
	}

	@Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (UIListAdapter.getDeviceList().size() <= arg2) {
			return; // fix bug
		}
		mDevice = UIListAdapter.getDeviceList().get(arg2);
		if (mBluetoothLeService != null) {
			txRssi.setText("正在连接");
			mBluetoothLeService.connect(mDevice.getAddress());
		}

		hiddenScanDeviceListView();

		layoutReSearch.setVisibility(View.GONE);

		mBesideHandler.removeMessages(MSG_STOP_SCAN_BY_TIME_OUT);
	}

	/******************* part bleService ********************/
	public BluetoothLeService getBluetoothLeService() {
		return mBluetoothLeService;
	}

	private BluetoothLeService mBluetoothLeService;
	private BluetoothDevice mDevice;

	public void updateUIAboutDeviceInfo(double distance) {
		if (txBleDevice.getTag() == null ) {
			DBLDebug.loge("updateUIAboutDeviceInfo to resetBleDeviceName");
			resetBleDeviceName();
		}

		if (imgBleDevice.getTag() == null ) {
			if (mBluetoothLeService != null) {
				String imei = Preferences.getImeiForMac( mBluetoothLeService.getBluetoothDeviceAddress());
				DBLDebug.loge("updateUIAboutDeviceInfo to resetBleDeviceHead");
				resetBleDeviceHead(imei);
			}
		}

		layoutDuanKai.setEnabled(true);
		layoutReSearch.setVisibility(View.GONE);
		layoutBleDevicePart.setVisibility(View.VISIBLE);
		layoutDeviceFun.setVisibility(View.VISIBLE);

		// test
		txDebugData.setVisibility(View.VISIBLE);
		txDebugData.setText(getProtectInfo(distance));

		if (!isHidden) {
			((MainActivity) holder).btnBleSet.setVisibility(View.VISIBLE);
		}
	}

	private String getProtectInfo(double distance) {
		String info = "";
		if (mBluetoothLeService != null) {
			String address = mBluetoothLeService.getBluetoothDeviceAddress();
			boolean isFangdiu = Preferences.getBleDeviceFangdiu(holder, address);
			int fangdiuJuli = Preferences.getBleDeviceFangdiuJuli(holder, address);
			boolean isFangdiuDuankai = Preferences.getBleDeviceFangdiuDuankai(holder, address);
			info = "防丢保护 ： " + (isFangdiu ? "开启" : "未开启");
			if (isFangdiu) {
//				info += "\n" + "保护距离 ： " + fangdiuJuli + "m";
				info += "\n" + "断开报警 ： " + (isFangdiuDuankai ? "开启" : "未开启");
//				info += "\n" + "tip: 最后距离两次超过设定值触发报警";
//				String dis = String.valueOf(distance);
//				if (dis.length() > 5) {
//					dis = dis.substring(0, 5);
//				}
//				info += "\n" + "最后距离：" + dis + "m";
			}
		}

		return info;
	}

	public boolean isConnected() {
		if (mBluetoothLeService != null) {
			return mBluetoothLeService.isConnected();
		}
		return false;
	}

	public void disconnectBLE() {
		if (layoutDuanKai != null) {
			layoutDuanKai.performClick();
		}
		if(mBluetoothLeService != null){
			mBluetoothLeService.disconnect();
		}
		doUIupdate(false);
		layoutReSearch.setVisibility(View.GONE);
	}

	public void requestScanBLE() {
		if (layoutReSearch != null) {
			layoutReSearch.performClick();
		}
		radarView.startScanning();
		
		if(mBluetoothLeService != null){
			mBluetoothLeService.disconnect();
		}
		layoutBleDevicePart.setVisibility(View.INVISIBLE);
		layoutDeviceFun.setVisibility(View.GONE);
		
	}

	private void doUIupdate() {
		DBLDebug.logd("BesideFragment doUIupdate()");
		boolean isConnected = false;
		if (mBluetoothLeService != null) {
			DBLDebug.logd("mConnectionState mBluetoothLeService.isConnecting()" + mBluetoothLeService.isConnecting() + ",getConnectionState" + mBluetoothLeService.getConnectionState());
			
			if (mBluetoothLeService.isConnecting()) {
				// 正在获取服务
				radarView.stopScanning();
				hiddenScanDeviceListView();
				txRssi.setText("正在连接"); 
				return;
			} else {
				txRssi.setText("无信号");
				isConnected = mBluetoothLeService.isConnected();
			}
		}
		doUIupdate(isConnected);
	}

	private void doUIupdate(boolean isConnected) {
		DBLDebug.logd("BesideFragment doUIupdate( " + isConnected + " )");
		radarView.stopScanning();
		hiddenScanDeviceListView();

		if (isConnected) {
			layoutDuanKai.setEnabled(true);
			layoutReSearch.setVisibility(View.GONE);
			layoutBleDevicePart.setVisibility(View.VISIBLE);
			layoutDeviceFun.setVisibility(View.VISIBLE);

			layoutCall.setTag("call");
			txCall.setText(R.string.call);

			if (!isHidden) {
				((MainActivity) holder).btnBleSet.setVisibility(View.VISIBLE);
			}
			if (mDevice != null) {
				txBleDevice.setText(mDevice.getName());
			}
			if (mBluetoothLeService != null) {
				String imei = Preferences.getImeiForMac(mBluetoothLeService.getBluetoothDeviceAddress());
				if (!TextUtils.isEmpty(imei)) {
					DBLDebug.loge("doUIupdate to resetBleDeviceHead");
					resetBleDeviceHead(imei);
				}
			}

		} else {
			layoutReSearch.setVisibility(View.VISIBLE);
			layoutBleDevicePart.setVisibility(View.INVISIBLE);
			layoutDeviceFun.setVisibility(View.GONE);
			mDevice = null;
			txRssi.setText("无信号");
			((MainActivity) holder).btnBleSet.setVisibility(View.GONE);
			
			txDebugData.setVisibility(View.VISIBLE);
			txDebugData.setText("蓝牙配对前请连续快速按三次随意找按键至长响一声开启蓝牙");
		}

	}

	private Bitmap localBitmap = null;
	
	private void resetBleDeviceHead(String imei, boolean mandatory){
		DBLDebug.logd("BesideFragment resetBleDeviceHead() imei:" + imei);
		if (!TextUtils.isEmpty(imei) ) {
			String tag = imgBleDevice.getTag() == null ? "" : imgBleDevice.getTag().toString();
			if((!imei.equals(tag) && holder != null ) || mandatory){
				String head64 = Preferences.getDeviceImgBase64(holder, imei);
				if (!TextUtils.isEmpty(head64)) {
					localBitmap = ImageUtils.base64ToBitmap(head64.replaceAll(getResources().getString(R.string.add_mark), "+"));
					if(localBitmap != null){
						imgBleDevice.setImageBitmap(ImageUtils.toRoundBitmap(localBitmap));
						imgBleDevice.postInvalidate();
						imgBleDevice.setTag(imei);
					}else{
						imgBleDevice.setImageResource(R.drawable.location3);
						imgBleDevice.setTag(imei);
					}
				}else{
					imgBleDevice.setImageResource(R.drawable.location3);
					imgBleDevice.setTag(imei);
				}
			}else{
				if(localBitmap != null){
					imgBleDevice.setImageBitmap(ImageUtils.toRoundBitmap(localBitmap));
					imgBleDevice.postInvalidate();
				}else{
					imgBleDevice.setImageResource(R.drawable.location3);
					imgBleDevice.postInvalidate();
				}
			}
		} else {
			imgBleDevice.setImageResource(R.drawable.location3);
		}
	}

	private void resetBleDeviceHead(String imei) {
		resetBleDeviceHead(imei, false);
	}

	private boolean resetBleDeviceName() {
		if (holder != null && mBluetoothLeService != null) {
			String imei = Preferences.getImeiForMac(mBluetoothLeService.getBluetoothDeviceAddress());
			if(TextUtils.isEmpty(imei)) { // 暂未绑定
				txBleDevice.setText(R.string.my_device);
				txBleDevice.setTag(txBleDevice.getText().toString());
				return false;
			}
			DBLDebug.logd("BesideFragment resetBleDeviceName() imei:" + imei);
			if (DBLApplication.getInstance().deviceInfoList != null) {
				for (DeviceInfo di : DBLApplication.getInstance().deviceInfoList) {
					if (di.imei.equals(imei) && !TextUtils.isEmpty(di.imei)) {
						txBleDevice.setText(di.name);
						txBleDevice.setTag(txBleDevice.getText().toString());
						return true;
					}
				}
			}
		}
		return false;
	}

	/* server */

	private void startBleService() {
		if (holder != null) {
			Intent gattServiceIntent = new Intent(holder, BluetoothLeService.class);
			holder.startService(gattServiceIntent);
			
			
		}
	}

	private boolean isBindBleService = false;

	private void bindBLeService() {
		if (holder != null && !isBindBleService) {
			isBindBleService = true;
			Intent gattServiceIntent = new Intent(holder, BluetoothLeService.class);
			holder.bindService(gattServiceIntent, mServiceConnection, Activity.BIND_AUTO_CREATE);
		}
	}

	private void unBindBLeService() {
		if (holder != null && isBindBleService) {
			isBindBleService = false;
			holder.unbindService(mServiceConnection);
			mBluetoothLeService = null;
		}
	}

	private final ServiceConnection mServiceConnection = new ServiceConnection() {

		@Override public void onServiceConnected(ComponentName componentName, IBinder service) {
			DBLDebug.logd("BesideFragment mBluetoothLeService Connected");

			mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();

			if (holder != null && SystemUtils.supportBLE(holder) && !mBluetoothLeService.isEnable()) {
				txSearch.setText(R.string.open_bluetooth);
			} else {
				// fix 已经连接 . 注册两次。 出问题。
				if(holder != null && SystemUtils.supportBLE(holder)){
					if (!mBluetoothLeService.isConnected() && !mBluetoothLeService.isConnecting()) {
						layoutReSearch.performClick();
					}	
				}
			}
			
			if(mBluetoothLeService.getConnectionState() == BluetoothLeService.STATE_CONNECTED){
				String imei = Preferences.getImeiForMac(mBluetoothLeService.getBluetoothDeviceAddress());
				if (!TextUtils.isEmpty(imei)) {
					DBLDebug.loge("mServiceConnection to resetBleDeviceHead");
					resetBleDeviceHead(imei);
					DBLDebug.loge("updateUIAboutDeviceInfo to resetBleDeviceName");
					resetBleDeviceName();
				}
			}
		}

		@Override public void onServiceDisconnected(ComponentName componentName) {
			mBluetoothLeService = null;
		}
	};

	private boolean isRegisterBleReceiver = false;

	private void registerBleReceiver() {
		if (holder != null && !isRegisterBleReceiver) {
			IntentFilter intentFilter = new IntentFilter();
			intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
			intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
			intentFilter.addAction(BluetoothLeService.ACTION_READ_REMOTE_RSSI);
			intentFilter.addAction(BluetoothLeService.ACTION_READ_REMOTE_DISTANCE);

			holder.registerReceiver(mGattUpdateReceiver, intentFilter);
			isRegisterBleReceiver = true;
		}
	}

	private void unregisterBleReceiver() {
		if (holder != null && isRegisterBleReceiver) {
			holder.unregisterReceiver(mGattUpdateReceiver);
			isRegisterBleReceiver = false;
		}
	}

	private void showBindDialog(final String connMac) {
		final Dialog d = new Dialog(holder, R.style.Theme_Light_NoTitle_NoShadow_Dialog);
		d.setCancelable(false);
		d.setCanceledOnTouchOutside(false);

		View content = null;

		final ArrayList<DeviceInfo> dl = DBLApplication.getInstance().deviceInfoList;
		if (dl == null || dl.size() < 1) {
			// ..
			return;
		} else if (dl.size() == 1) {
			final DeviceInfo selectedD = dl.get(0);

			content = LayoutInflater.from(holder).inflate(R.layout.dialog_confirm_2, null);

			TextView txTitle = (TextView) content.findViewById(R.id.tx_title);
			txTitle.setText(R.string.bind_device);

			TextView txMessage = (TextView) content.findViewById(R.id.tx_message);
			txMessage.setText(String.format(getString(R.string.bind_device_for), selectedD.name));

			Button btnCancel = (Button) content.findViewById(R.id.btn_cancel);
			btnCancel.setText(R.string.cancel2);
			btnCancel.setOnClickListener(new OnClickListener() {
				@Override public void onClick(View arg0) {
					String imei = null;
					if(mBluetoothLeService != null) {
						String address = mBluetoothLeService.getBluetoothDeviceAddress();
						if(address != null) {
							imei = Preferences.getImeiForMac(address);
						}
					}
					resetBleDeviceHead(imei);
					resetBleDeviceName();
					d.dismiss();
				}
			});

			content.findViewById(R.id.btn_confirm).setOnClickListener(new OnClickListener() {
				@Override public void onClick(View arg0) {
					DBLDebug.loge("showBindDialog confirm to resetBleDeviceHead");
					Preferences.saveImeiForMac(holder, connMac, selectedD.imei);
					resetBleDeviceHead(selectedD.imei);
					resetBleDeviceName();
					d.dismiss();
				}
			});
		} else {
			content = LayoutInflater.from(holder).inflate(R.layout.dialog_device_list, null);

			TextView txTitle = (TextView) content.findViewById(R.id.tx_title);
			txTitle.setText(R.string.bind_device);

			ListView deviceList = (ListView) content.findViewById(R.id.listview);
			deviceList.setAdapter(new DeviceListAdapter());

			content.findViewById(R.id.btn_cancel).setOnClickListener(new OnClickListener() {
				@Override public void onClick(View arg0) {
					DBLDebug.loge("showBindDialog list devices ! btn_cancel");
					String imei = null;
					if(mBluetoothLeService != null) {
						String address = mBluetoothLeService.getBluetoothDeviceAddress();
						if(address != null) {
							imei = Preferences.getImeiForMac(address);
						}
					}
					resetBleDeviceHead(imei);
					resetBleDeviceName();
					d.dismiss();
				}
			});

			deviceList.setOnItemClickListener(new OnItemClickListener() {
				@Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
					DeviceInfo selectedD = dl.get(position);
					Preferences.saveImeiForMac(holder, connMac, selectedD.imei);
					DBLDebug.loge("showBindDialog setOnItemClickListener to resetBleDeviceHead");
					resetBleDeviceHead(selectedD.imei);
					d.dismiss();
				}
			});

		}

		d.setContentView(content);
		d.show();
	}

	class DeviceListAdapter extends BaseAdapter {
		@Override public int getCount() {
			return DBLApplication.getInstance().deviceInfoList == null ? 0 : DBLApplication.getInstance().deviceInfoList.size();
		}

		@Override public Object getItem(int arg0) {
			return DBLApplication.getInstance().deviceInfoList == null ? null : DBLApplication.getInstance().deviceInfoList.get(arg0);
		}

		@Override public long getItemId(int arg0) {
			return arg0;
		}

		@Override public View getView(int position, View view, ViewGroup arg2) {
			final DeviceInfo device = DBLApplication.getInstance().deviceInfoList.get(position);
			if (view == null) {
				view = LayoutInflater.from(getActivity()).inflate(R.layout.listitem_device_info, null);
			}
			((TextView) view).setText(device.name);
			view.setTag(position);

			return view;
		}
	}

	Dialog rebindD;

	private void showRenindDialog(final String connMac, final String rebindImei) {
		// 不知道为什么蓝牙成功连接广播发两次成功，但是只能同时存在一个 所以
		if (rebindD != null && rebindD.isShowing()) {
			return;
		}
		// 弹出框后重置imei，避免重复出现绑定提示
		((MainActivity) holder).rebindImei = "";

		rebindD = new Dialog(holder, R.style.Theme_Light_NoTitle_NoShadow_Dialog);
		rebindD.setCancelable(false);
		rebindD.setCanceledOnTouchOutside(false);

		String rebindDeviceName = "";
		if (DBLApplication.getInstance().deviceInfoList != null) {
			for (DeviceInfo di : DBLApplication.getInstance().deviceInfoList) {
				if (di.imei.equals(rebindImei)) {
					rebindDeviceName = di.name;
					break;
				}
			}
		}
		View content = LayoutInflater.from(holder).inflate(R.layout.dialog_confirm_2, null);

		TextView txTitle = (TextView) content.findViewById(R.id.tx_title);
		txTitle.setText(R.string.bind_device);

		TextView txMessage = (TextView) content.findViewById(R.id.tx_message);
		txMessage.setText(String.format(getString(R.string.bind_device_for), rebindDeviceName));

		Button btnCancel = (Button) content.findViewById(R.id.btn_cancel);
		btnCancel.setText(R.string.cancel2);
		btnCancel.setOnClickListener(new OnClickListener() {
			@Override public void onClick(View arg0) {
				rebindD.dismiss();
			}
		});

		content.findViewById(R.id.btn_confirm).setOnClickListener(new OnClickListener() {
			@Override public void onClick(View arg0) {
				Preferences.saveImeiForMac(holder, connMac, rebindImei);
				DBLDebug.loge("showRenindDialog confirm to resetBleDeviceHead");
				resetBleDeviceHead(rebindImei);
				rebindD.dismiss();
			}
		});

		rebindD.setContentView(content);
		rebindD.show();
	}

	@Override public void onResume() {
		super.onResume();
	}

	@Override public void onPause() {
		super.onPause();
	}

	@Override public void onDestroy() {
		super.onDestroy();
		
		if(radarView.isScanning()){
			if(mBluetoothLeService != null){
				mBluetoothLeService.stopLeScan(mLeScanCallback);	
				mBluetoothLeService.releaseGatt();
				
//				mBluetoothLeService.cancelDiscovery();
				
				mBesideHandler.removeMessages(MSG_STOP_SCAN_BY_TIME_OUT);
			}
		}
		
		unregisterBleReceiver();
		stopScanDeviceList();
		unBindBLeService();
	}

	private boolean hidden = true;

	@Override public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		this.hidden = hidden;
		if (!hidden && holder != null) {
			((MainActivity) holder).hiddenWaitingMessage();
			((MainActivity) holder).btnBleSet.setVisibility(isConnected() ? View.VISIBLE : View.GONE);
		}
	}
	
	private Dialog dlgRemindBleOpen ;
	private void showRemindBleOpenDialog(){
		dlgRemindBleOpen = new Dialog(holder, R.style.Theme_Light_NoTitle_Dialog);
		dlgRemindBleOpen.setCancelable(true);
		dlgRemindBleOpen.setCanceledOnTouchOutside(true);

		View content = LayoutInflater.from(holder).inflate(R.layout.dialog_remind_ble_open, null);
		
		final CheckBox ckRemind = (CheckBox) content.findViewById(R.id.ck_remind);
		
		TextView txMessage =  (TextView) content.findViewById(R.id.  tx_message);
		txMessage.setText(R.string.ble_remind_open);
		
		content.findViewById(R.id.btn_confirm).setOnClickListener(new OnClickListener() {
			@Override public void onClick(View v) {
				if(ckRemind.isChecked()){
					Preferences.saveIs2RemindBleOpen(false);
				}
				
				if(dlgRemindBleOpen != null){
					dlgRemindBleOpen.dismiss();
					dlgRemindBleOpen = null;
				}
			}
		});
		
		dlgRemindBleOpen.setContentView(content);
		dlgRemindBleOpen.show();
	}
	
	public void toShowFirstRemindInfo(){
		DBLDebug.loge("Preferences.getIs2RemindBleOpen():" + Preferences.getIs2RemindBleOpen());
		if(Preferences.getIs2RemindBleOpen()){
			showRemindBleOpenDialog();
		}
	}
}
